<script lang="ts">
	import { onMount } from 'svelte';
	import Portal from 'svelte-portal';
	import { ensurePortalContainer } from '$lib/utils/container/ensurePortalContainer';
	import Scrollbar from '$lib/components/Basic/Scrollbar/Scrollbar.svelte';
	import RectButton from '$lib/components/Basic/Button/RectButton.svelte';
	import { fly, fade } from 'svelte/transition';

	const getTransitionOptions = () => {
		switch (direction) {
			case 'right':
				return { duration: 300, x: '100%' };
			case 'left':
				return { duration: 300, x: '-100%' };
			case 'top':
				return { duration: 300, y: '-100%' };
			case 'bottom':
				return { duration: 300, y: '100%' };
		}
	};

	const {
		open = false,
		title = '',
		direction = 'right',
		withOverlay = true,
		size = '30%',
		closeOnClickOverlay = true,
		onClose = () => {},
		children
	} = $props<{
		open?: boolean;
		title?: string;
		direction?: 'right' | 'left' | 'top' | 'bottom';
		withOverlay?: boolean;
		size?: string;
		closeOnClickOverlay?: boolean;
		onClose?: () => void;
		children?: any;
	}>();

	let portalContainer: HTMLElement | undefined = $state();
	// 用于聚焦管理（提升可访问性）
	let overlayRef: HTMLDivElement | null = $state(null);

	// 统一的关闭处理（支持键盘和鼠标事件）
	const handleInteraction = (e: MouseEvent | KeyboardEvent) => {
		// 键盘事件：仅响应 Enter 或 Space 键
		if (e instanceof KeyboardEvent && !['Escape'].includes(e.key)) {
			return;
		}
		closeOnClickOverlay && onClose();
		// 阻止键盘事件冒泡和默认行为（如 Space 键滚动页面）
		e.preventDefault();
		e.stopPropagation();
	};

	// 抽屉打开时自动聚焦到遮罩层（方便键盘操作）
	$effect(() => {
		if (open && overlayRef && withOverlay) {
			overlayRef.focus();
		}
	});

	onMount(() => {
		portalContainer = ensurePortalContainer('draw-container');
	});
</script>

{#if open}
	<Portal target={portalContainer}>
		<div
			bind:this={overlayRef}
			class="drawer-overlay"
			class:drawer-overlay--not-show={!withOverlay}
			onclick={handleInteraction}
			onkeydown={handleInteraction}
			role="button"
			tabindex={open ? 0 : -1}
			aria-label="关闭抽屉"
			transition:fade={{ duration: 300 }}
		></div>
		<div
			class="drawer-container drawer--{direction}"
			transition:fly={getTransitionOptions()}
			style="{direction === 'left' || direction === 'right'
				? `width: ${size}`
				: `height: ${size}`};"
			role="dialog"
			aria-modal="true"
			aria-labelledby={title ? 'drawer-title' : undefined}
		>
			{#if title}
				<div class="drawer-header">
					<h3 class="drawer-title" id="drawer-title">{title}</h3>
					<!-- 标题添加id用于关联 -->
					<!-- 2. 关闭按钮用<button>替代<div>（更语义化） -->
					<RectButton
						icon="symbol/close"
						type="text"
						onClick={onClose}
						iconSize={20}
						style="padding:2px;height: 24px;"
					></RectButton>
				</div>
			{/if}

			<div class="drawer-content" class:drawer-content--no-header={!title}>
				<Scrollbar scrollWidth={8} scrollPadding={4}>
					{@render children()}
				</Scrollbar>
			</div>
		</div>
	</Portal>
{/if}

<style scoped>
	/* 样式保持不变 */
	.drawer-overlay {
		position: fixed;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		background-color: var(--color-overlay);
		z-index: 50;
		pointer-events: auto;
	}
	.drawer-overlay--not-show {
		background-color: transparent;
	}
	.drawer-container {
		position: fixed;
		background-color: var(--color-page);
		box-shadow: 0 0 20px var(--color-shadow);
		z-index: 51;
		overflow: hidden;
		pointer-events: auto;
	}
	.drawer--right {
		top: 0;
		right: 0;
		height: 100vh;
		border-radius: 8px 0 0 8px;
	}
	.drawer--left {
		top: 0;
		left: 0;
		height: 100vh;
		border-radius: 0 8px 8px 0;
	}
	.drawer--top {
		top: 0;
		left: 0;
		width: 100vw;
		border-radius: 0 0 8px 8px;
	}
	.drawer--bottom {
		bottom: 0;
		left: 0;
		width: 100vw;
		border-radius: 8px 8px 0 0;
	}
	.drawer-header {
		height: 50px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 18px;
		border-bottom: var(--border);
	}
	.drawer-title {
		font-size: 16px;
		font-weight: 500;
		font-family: Arial, Helvetica, sans-serif;
		color: var(--color-info-900);
	}
	.drawer-close-btn {
		border: none;
		height: 24px;
		width: 24px;
		padding: 0;
		border-radius: 6px;
		cursor: pointer;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.drawer-content {
		height: round(calc(100% - 50px), 1px);
	}
	.drawer-content.drawer-content--no-header {
		height: round(100%, 1px);
	}
</style>
